<?php
//рус
class MozgDB extends PDO
{
	protected $_tablePrefix = '';
	protected $_tablesList = array();
	protected $_tablesPlaceList = array();
	
	public function __construct()
	{
		$args = func_get_args();
		call_user_func_array(array(parent, '__construct'), $args);
		
		$tables = (array)$this->getDBTablesCached();
		$this->_tablesList = array_values($tables);
		$this->_tablesPlaceList = array_keys($tables);
	}
	
	protected function getDBTablesCached()
	{
		list(,$sourceName) = explode('_', get_class($this), 2);
		$cacheDbFile = _CACHE_PATH. '_db/' .strtolower($sourceName). '_tablesList.php';
		
		if (is_file($cacheDbFile)) 
		{
			$tables = include($cacheDbFile);
			if (isset($tables[$this->_tablePrefix])) return $tables[$this->_tablePrefix];	
		}
		
		$tables = $this->getDBTables();

		$path = pathinfo($cacheDbFile);
		if ((is_file($cacheDbFile) && !is_writable($cacheDbFile)) || !SysLoader::GetLibCollection()->dir->Create($path['dirname'])) 
		{
			return $tables[$this->_tablePrefix];			
		}
		
		$fileContent = '<?php return ' .var_export($tables, TRUE). ';';
		
		file_put_contents($cacheDbFile, $fileContent);	

		return $tables[$this->_tablePrefix];
	}
	
	protected function getDBTables()
	{
		$stmt = $this->query('show tables');
		if (!$stmt) return array();

		$stmt->setFetchMode(PDO::FETCH_COLUMN, 0);
		$tables = $stmt->fetchAll();
		
		$tablePrefix = $this->_tablePrefix. '_';
		$prefLength = strlen($tablePrefix);
		
		$myTables = array();
		foreach ($tables as $table)
		{
			if ($prefLength && strpos($table, $tablePrefix) !== 0) continue;
			$nTable = substr($table, $prefLength);
			$myTables['%%' .$nTable. '%%'] = $table;
		}
		
		return array($this->_tablePrefix => $myTables);
	}
	
	public function prepare()
	{
		$args = func_get_args();
		return $this->executeQueryFunction($args, 'prepare');
	}

	public function query()
	{
		$args = func_get_args();
		return $this->executeQueryFunction($args, 'query');
	}	

	public function exec()
	{
		$args = func_get_args();
		return $this->executeQueryFunction($args, 'exec');
	}	
	
	protected function executeQueryFunction($args, $funcName)
	{
		$args[0] = $this->replaceTableMarkers($args[0]);
		
		$result = call_user_func_array(array(parent, $funcName), $args);
		if (!$result) $this->handleError();
		
		return $result;		
	}
	
	protected function replaceTableMarkers($query)
	{
		return str_replace($this->_tablesPlaceList, $this->_tablesList, $query);
	}
	
	protected function handleError()
	{
		$error = $this->errorInfo();
		if (!is_null($error[1])) throw new Exception("MySQL error: code = " .$error[1]. "; message = " .$error[2]);
	}
}    
    
